<template>
	<view class="wrap-container">
		<u-navbar ref="navbarRef" class="van-nav-bar" :placeholder="true" title="测评题" @leftClick="leftClick" :autoBack="false"></u-navbar>
		<view :style="{ height: domHeight }" class="cantainer">
			<view class="head">
				<image :src="$buildFullImageUrl('/static/evaluate/question.svg')"></image>
				<view class="line-poss">
					<liu-progressbar :textInside="false" :progress="processNum" bgColor="#5C83FD" dsColor="#e5e5e5" color="#FFFFFF" :height="'10rpx'" />
				</view>
				<view>
					<text>{{ selQuestionIndex + 1 }}</text>
					<text>/</text>
					<text>{{ list.length }}</text>
				</view>
			</view>
			<view class="question">
				<jumpQuestions @checkedNow="checkedNow" @singleNow="singleNow" :question="question" :selQuestionIndex="selQuestionIndex"></jumpQuestions>
			</view>
			<view class="bot-wrap">
				<view v-if="selQuestionIndex === 0" class="all-next" @click="handleNext">下一题</view>
				<view v-if="selQuestionIndex !== 0" class="prev" @click="handlePrev">上一题</view>
				<view v-if="selQuestionIndex !== 0" class="next" @click="handleNext">下一题</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getTopicList, appraisalAnswer, getAppraisal, getUserAppraisalList } from '@/api/evaluate/index.js';
import jumpQuestions from '@/components/jump-question/jump-question.vue';
import { getNowTime, calculateScores, calculateScore, calculateTotal, extractFilteredObjects, filterFields } from '@/utils/common.js';
export default {
	data() {
		return {
			isSubmitting: false,
			domHeight: '',
			question: {},
			selQuestionIndex: -1, //当前选择题目下标，默认第一条
			list: [],
			appraisalBeginDate: getNowTime(),
			appraisalId: '',
			appraisalName: '',
			processNum: 0,
			appraisalDataCopy: [],
			dataId: ''
		};
	},
	components: {
		jumpQuestions
	},
	onLoad(options) {
		this.appraisalId = options.id;

		// 启动心跳
		this.startHeartbeat();

		// 监听全局异常事件
		this.abnormalHandler = (path) => {
			if (path === this.$mp.page.route) {
				this.handleAbnormalExit();
			}
		};
		uni.$on('page-abnormal', this.abnormalHandler);
	},
	onShow() {
		getTopicList(this.appraisalId).then((res) => {
			this.list = res.rows;
			//查询用户测评列表
			getUserAppraisalList({
				appraisalId: this.appraisalId,
				userId: uni.getStorageSync('user_id'),
				appraisalStatus: '0'
			}).then((res) => {
				if (res.rows.length !== 0) {
					if (res.rows[0].appraisalData !== '') {
						//有数据
						// console.log(res.rows);
						this.dataId = res.rows[0].id;
						this.appraisalDataCopy = JSON.parse(res.rows[0].appraisalData);
						this.selQuestionIndex = res.rows[0].appraisalStage * 1;
						this.appraisalName = res.rows[0].appraisalName;

						this.list.map((i) => {
							this.appraisalDataCopy.map((m) => {
								if (i.id === m.id) {
									if (m.selSingle) {
										i.selSingle = m.selSingle;
									}
									if (m.hasOwnProperty('selChecked')) {
										if (m.selChecked.length !== 0) {
											i.selChecked = m.selChecked;
										}
									}
								}
							});
						});
						// console.log(this.list);
					}
				} else {
					this.selQuestionIndex = 0;
					this.dataId = '';
					getAppraisal(this.appraisalId).then((res) => {
						// console.log(res);
						this.appraisalName = res.data.appraisalName;
					});
				}

				// console.log(res);
			});
		});
	},
	watch: {
		selQuestionIndex() {
			this.question = this.list[this.selQuestionIndex];
			this.processNum = this.calculatePercentage(this.selQuestionIndex + 1, this.list.length);
		}
	},
	methods: {
		singleNow(e) {
			if (this.isSubmitting) return; // 如果正在提交，直接返回
			this.list[this.selQuestionIndex].selSingle = e.id;
			// console.log(this.list);

			if (this.list.length - 1 === this.selQuestionIndex) {
				this.isSubmitting = true; // 加锁
				// console.log(calculateTotal(calculateScores(this.list)));
				this.postAnswer();
			} else {
				this.selQuestionIndex += 1;
			}
		},
		checkedNow(item) {
			this.list[this.selQuestionIndex].selChecked = item;
		},
		handleNext() {
			//主要是多选
			if (this.list[this.selQuestionIndex].choiceStatus === '0') {
				if (!this.list[this.selQuestionIndex].selSingle) {
					this.$modal.showToast('请选择答案');
				} else {
					this.selQuestionIndex += 1;
				}
			} else if (this.list[this.selQuestionIndex].choiceStatus === '1') {
				//多选并且答案数组长度不为空
				if (this.list[this.selQuestionIndex].hasOwnProperty('selChecked')) {
					if (this.list[this.selQuestionIndex].selChecked.length !== 0) {
						// console.log('不为空且有值')
						if (this.list.length - 1 === this.selQuestionIndex) {
							// console.log('已经最后一题目，跳转到结果分析页面');
							this.postAnswer();
						} else {
							this.selQuestionIndex += 1;
							// console.log('下一题');
						}
					} else {
						// console.log('不为空但没值')
						this.$modal.showToast('请选择答案');
					}
				} else {
					// console.log('空的');
					this.$modal.showToast('请选择答案');
				}
			}
		},
		handlePrev() {
			this.selQuestionIndex -= 1;
		},
		postAnswer() {
			// 提交完成后解锁
			this.isSubmitting = false;
			let userAppraisalDivisorList = [];
			this.list.forEach((i) => {
				userAppraisalDivisorList.push({
					divisorId: i.divisorId,
					divisorScore: calculateScore(i)
				});
			});

			const mergedData = Object.values(
				userAppraisalDivisorList.reduce((resultMap, currentItem) => {
					// 如果当前id已存在，则累加score
					if (resultMap[currentItem.divisorId]) {
						resultMap[currentItem.divisorId].divisorScore += currentItem.divisorScore;
					}
					// 如果不存在，则创建新条目
					else {
						resultMap[currentItem.divisorId] = {
							...currentItem
						};
					}
					return resultMap;
				}, {}) // 初始值是一个空对象
			);

			const mergedData2 = Object.values(
				userAppraisalDivisorList.reduce((resultMap, currentItem) => {
					const divisorId = currentItem.divisorId;

					if (resultMap[divisorId]) {
						// 存在时：累加分数 + 计数 + 更新平均分
						resultMap[divisorId].divisorScore += currentItem.divisorScore;
						resultMap[divisorId].count += 1;
						resultMap[divisorId].averageScore = (resultMap[divisorId].divisorScore / resultMap[divisorId].count).toFixed(this.appraisalId == 8 ? 1 : 2);
					} else {
						// 不存在时：创建新条目（包含计数和平均分）
						resultMap[divisorId] = {
							...currentItem,
							count: 1,
							averageScore: currentItem.divisorScore.toFixed(this.appraisalId == 8 ? 1 : 2)
						};
					}
					return resultMap;
				}, {})
			);

			let finallData = [];
			mergedData2.map((i) => {
				finallData.push({
					divisorId: i.divisorId,
					divisorScore: i.averageScore
				});
			});

			// console.log(extractFilteredObjects(this.list, ['id', 'score']).length);
			// console.log(Number(calculateTotal(calculateScores(this.list))) / extractFilteredObjects(this.list, ['id', 'score']).length);
			appraisalAnswer({
				appraisalBeginDate: this.appraisalBeginDate,
				appraisalData: '', //中途退出存储数据
				appraisalFinishDate: getNowTime(),
				appraisalId: this.appraisalId,
				appraisalName: this.appraisalName,
				appraisalScore:
					this.appraisalId == 4
						? (Number(calculateTotal(calculateScores(this.list))) / extractFilteredObjects(this.list, ['id', 'score']).length).toFixed(2)
						: calculateTotal(calculateScores(this.list)), //测评结果最终得分
				appraisalStage: '', //所处阶段
				appraisalStatus: '1',
				id: this.dataId ? this.dataId : '',
				userSex: uni.getStorageSync('user_sex'),
				userAppraisalAnswerList: extractFilteredObjects(this.list, ['id', 'score']),
				userAppraisalDivisorList: this.appraisalId == 4 || this.appraisalId == 8 ? finallData : mergedData
			}).then((res) => {
				this.$tab.navigateTo(`/subset/pages/evaluate/evaluateResult?appraisalId=${this.appraisalId}&id=${res.data.id}`);
			});
		},
		// 启动心跳定时器
		startHeartbeat() {
			this.stopHeartbeat(); // 防止重复启动
			this.heartbeatTimer = setInterval(() => {
				uni.$emit('heartbeat', this.$mp.page.route);
			}, 2000); // 每2秒发送一次心跳
		},

		// 停止心跳
		stopHeartbeat() {
			if (this.heartbeatTimer) {
				clearInterval(this.heartbeatTimer);
				this.heartbeatTimer = null;
			}
		},

		// 异常处理逻辑
		handleAbnormalExit() {
			// console.log('检测到页面异常退出，执行清理操作');
			this.badEnd();
			console.log('页面异常退出');
			// 示例1：保存未提交数据
			// uni.setStorageSync('abnormal-data', this.customData);

			// 示例2：清理定时器
			this.stopHeartbeat();

			// 示例3：重置页面状态
			// this.customData = '';

			// 示例4：跳转提示页（需根据业务需求决定是否执行）
			// uni.redirectTo({ url: '/pages/error-page' });
		},
		calculatePercentage(part, total, decimals = 2) {
			if (typeof part !== 'number' || typeof total !== 'number') {
				return 'Invalid input';
			}

			if (total === 0) {
				return part === 0 ? '0.00%' : 'NaN%'; // 处理除零异常
			}

			const percentage = (part / total) * 100;
			return `${percentage.toFixed(decimals)}`;
		},
		//断点续传
		badEnd() {
			if (this.list.length > this.selQuestionIndex + 1 && this.selQuestionIndex > 0) {
				let appraisalDataJson = [];
				this.list.forEach((i) => {
					if (i.selSingle) {
						appraisalDataJson.push({
							id: i.id,
							selSingle: i.selSingle
						});
					}
					if (i.hasOwnProperty('selChecked') && i.selChecked.length !== 0) {
						appraisalDataJson.push({
							id: i.id,
							selChecked: i.selChecked
						});
					}
				});
				// console.log('我是断点的数据');
				// console.log(appraisalDataJson);
				// return
				appraisalAnswer({
					appraisalBeginDate: this.appraisalBeginDate,
					appraisalData: JSON.stringify(appraisalDataJson), //中途退出存储数据
					appraisalFinishDate: getNowTime(),
					id: this.dataId ? this.dataId : '',
					appraisalId: this.appraisalId,
					appraisalName: this.appraisalName,
					// appraisalScore: calculateTotal(calculateScores(this.list)), //测评结果最终得分
					appraisalStage: this.selQuestionIndex, //所处阶段
					appraisalStatus: '0',
					userSex: uni.getStorageSync('user_sex')
				}).then((res) => {
					// console.log(res);
				});
			}
		},
		leftClick() {
			uni.showModal({
				title: '提示',
				content: '您还未完成测评，是否需要退出？',
				success: (res) => {
					if (res.confirm) {
						this.$tab.navigateBack();
					} else if (res.cancel) {
						// this.$modal.showToast('已取消');
					}
				}
			});
		}
	},
	onUnload() {
		//断点续传
		this.badEnd();
		console.log('页面正常退出');
		// 页面卸载时清理资源
		this.stopHeartbeat();
		uni.$off('page-abnormal', this.abnormalHandler);
	},
	mounted() {
		const systemInfo = uni.getSystemInfoSync();
		let statusBarHeight = systemInfo.statusBarHeight || 20;
		// 示例计算公式（具体需根据组件实现调整）
		const height = statusBarHeight + 44 + 'px'; // 状态栏高度 + 导航栏内容高度
		this.domHeight = `calc(100% - ${height})`;
	}
};
</script>

<style scoped lang="scss">
.wrap-container {
	width: 100%;
	height: 100%;
	background-color: #e9e9e9;
	padding: 16rpx 20rpx;
	box-sizing: border-box;
}

.cantainer {
	.head {
		width: 100%;
		height: 80rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #fff;
		padding: 0 20rpx;
		box-sizing: border-box;
		border-radius: 10rpx;

		image {
			width: 50rpx;
			height: 50rpx;
		}

		.line-poss {
			width: calc(100% - 150rpx);
		}

		> view:last-child {
			> text:nth-child(1) {
				color: #000;
				font-size: 40rpx;
			}

			> text:nth-child(2),
			:nth-child(3) {
				color: #afafaf;
				font-size: 30rpx;
			}
		}
	}

	.question {
		margin-top: 16rpx;
		width: 100%;
		background-color: #fff;
		border-radius: 10rpx;
		max-height: calc(100% - 96rpx - 16rpx - 166rpx);
		overflow-y: auto;
	}

	.bot-wrap {
		width: 100%;
		height: 166rpx;
		background: rgba(255, 255, 255, 1);
		position: fixed;
		bottom: 0;
		left: 0;
		padding: 24rpx 30rpx 58rpx 32rpx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.all-next {
			width: 100%;
			height: 84rpx;
			text-align: center;
			line-height: 84rpx;
			font-weight: bold;
			font-size: 28rpx;
			color: #ffffff;
			background: #5c83fd;
			border-radius: 42rpx;
		}

		.prev {
			width: 35%;
			height: 84rpx;
			text-align: center;
			line-height: 84rpx;
			font-weight: bold;
			font-size: 28rpx;
			color: #000;
			background: #ecedf0;
			border-radius: 42rpx;
		}

		.next {
			width: calc(100% - 35% - 32rpx);
			height: 84rpx;
			text-align: center;
			line-height: 84rpx;
			font-weight: bold;
			font-size: 28rpx;
			color: #ffffff;
			background: #5c83fd;
			border-radius: 42rpx;
		}
	}
}
</style>
